# -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 10:29:20 2020

@author: xyz

存放vpc界面的函数

"""

#必备的包
import sys
import os
from PyQt5.QtWidgets import QWidget, QApplication, QFileDialog, QMessageBox
from PyQt5.QtCore import Qt
from fit import Fit
#fit界面的其他子界面
from window import MainWin
#nlmixr的包
from nlmixr import *

class CheckVpc(MainWin):
    def __init__(self):
        super().__init__()
        #用来存放需要绘制图形的变量名称
        self.plot_list_in_check = [] 
        #获取globalenv的按钮
        self.pushButton_5.clicked.connect(self.get_globalenv_in_check)
        self.pushButton_5.clicked.connect(self.display_globalenv_in_check)
        #获取选中变量的按钮 self.global_var_in_check是最终返回的被选中的var
        self.pushButton_4.clicked.connect(self.get_contents_in_lineEdit_2)
        #选中某个功能
        self.obs_dv.stateChanged.connect(self.choose_obs_dv)
        #生成pdf
        self.pushButton_6.clicked.connect(self.wait_three_minute)
        self.pushButton_6.clicked.connect(self.plot_it_in_check)
    
    def get_globalenv_in_check(self):
        #获取globalenv中的变量
        glonames = robjects.r.ls(globalenv)
        self.globalnames = []
        for x in glonames:
            self.globalnames.append(x)
            
    def display_globalenv_in_check(self):
        #显示globalenv中的变量
        self.textBrowser_2.setText('')
        for x in self.globalnames:
            self.textBrowser_2.append(x)
    
    def get_contents_in_lineEdit_2(self):
        #获取从lineEdit_2的输入的内容
        self.global_var_in_check = self.lineEdit_2.text()
        # print(type(self.global_var_in_check))
        QMessageBox.information(self,'提示','获取成功！',QMessageBox.Ok,QMessageBox.Ok)
        return self.global_var_in_check

    def choose_obs_dv(self,state):
        #当选择了obs_dv
        if state == Qt.Checked:
            self.plot_list_in_check.append('obs_dv')
        else:
            self.plot_list_in_check.remove('obs_dv')
    
    def wait_three_minute(self):
        QMessageBox.information(self,'提示','此过程大概需要三分钟',QMessageBox.Ok,QMessageBox.Ok)
        
    def plot_it_in_check(self):
        #作图
        self.pushButton_6.setEnabled(False)
        l = []
        robjects.r('''bins <- c(0, 3, 12, 24, 168, 171, 180, 192)''')
        robjects.r('''vpc.%s <- nlmixr::vpc(%s, nsim=700,show=list(obs_dv=T),
                   bins=bins)''' %(self.global_var_in_check,self.global_var_in_check))
        
        if 'obs_dv' in self.plot_list_in_check:
            vpc1 = robjects.r('''vpc1 = vpc.%s$gg +
      scale_x_continuous("Time (h)") +
        scale_y_continuous("Concentration")'''%self.global_var_in_check)
            l.append('vpc1,')
        else:
            l.append('')
        #保存图片
        pdf("fig2_%s.pdf" %self.global_var_in_check ,width=8,height=8)
        robjects.r('''grid.arrange(%s nrow=2)'''%(l[0]))
        dev_off()
        self.pushButton_6.setEnabled(True)
        QMessageBox.information(self,'提示','已保存至当前工作目录下',QMessageBox.Ok,QMessageBox.Ok)
        